package com.tanhua.sso.controller;

import com.tanhua.common.pojo.User;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.sso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 景银泰
 * date 2020-11-10 18:06
 * Description :手机验证码验证接口
 * Version :
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 根据token查询用户数据
     *
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.queryUserByToken(token);
    }


    @RequestMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String, String> param) {
        String mobile = param.get("phone");
        String code = param.get("verificationCode");
        System.out.println("*******************************");
        System.out.println("用户登录");
        System.out.println("手机号:" + mobile);
        System.out.println("验证码:" + code);

        String token = userService.login(mobile, code);
        System.out.println("服务层返回token:"+token);

        if (StringUtils.isNotEmpty(token)) {
            String[] split = StringUtils.split(token,"|");

            Boolean isNew = Boolean.valueOf(split[0]);
            String tokenstr = split[1];

            Map<String, Object> result = new HashMap<>();
            result.put("isNew", isNew);
            result.put("token", tokenstr);

            return ResponseEntity.ok(result);

        }

        ErrorResult.ErrorResultBuilder resultBuilder = ErrorResult.builder().errCode("000000").errMessage("验证码错误！");

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultBuilder.build());


    }

}
